<template>
    <div>
        <Card class="wrap" :bordered="false" :dis-hover="true">
            <Form :model="search" :label-width="80">
                <div class="table-top-wrap">
                    <div>
                        <div>
                            <Button class="features-btn" @click="handleBtnClick"  style="background:#009688;color:#fff">
                                <Icon type="md-add" size="18" />预约
                            </Button>
                            <Button class="features-btn btn-auto-m" @click="SchedulingBtn"  style="background:#009688;color:#fff">
                                <Icon type="md-calendar" size="18" />排期
                            </Button>
                        </div>
                    </div>
                    <div class="table-top-wrap-bottom">
                        <div class="table-top-wrapper">
                            <Select v-model="search.project" multiple placeholder="预约项目">
                                <Option v-for="item in project" :value="item.value" :key="item.value">{{ item.label }}</Option>
                            </Select>
                        </div>
                        <div class="table-top-wrapper">
                            <Select v-model="search.source" clearable placeholder="来源">
                                <Option v-for="item in source" :value="item.value" :key="item.value">{{ item.label }}</Option>
                            </Select>
                        </div>
                        <div class="table-top-wrapper">
                            <Select v-model="search.state" clearable placeholder="状态">
                                <Option v-for="item in state" :value="item.value" :key="item.value">{{ item.label }}</Option>
                            </Select>
                        </div>
                        <div class="table-top-wrapper">
                            <DatePicker type="date" placeholder="预约时间" style="width: 200px" v-model="search.date"></DatePicker>
                        </div>
                        <div>
                            <Button icon="ios-search" @click="handleSearch" class="search-btn"  style="background:#009688;color:#fff">搜索</Button>
                        </div>
                    </div>
                </div>
            </Form>
            <slot></slot>
            <Table :height="tableHeight" border :columns="columns" :data="list">
                <template slot-scope="{ row }" slot="BookDate">{{ row.BookDate | BookDateCn }}&nbsp;{{`${row.BookTime}:00`}}</template>
                <template slot-scope="{ row }" slot="InFrom">{{ row.InFrom | InFromCn }}</template>
                <template slot-scope="{ row }" slot="State">{{ row.State | stateCn }}</template>
                <template slot-scope="{ row }" slot="CreateTime">{{ row.CreateTime | CreateTimeCn }}</template>
                <template slot-scope="{ row }" slot="action">
                    <Button type="primary" size="small"  style="margin-right: 5px;background:#5ab1ef;color:#fff;border:#5ab1ef;" @click="ChangeAppointment(row)">修改</Button>
                    <Button
                        v-if="row.State!=='4'"
                        type="error"
                        size="small"
                        style="margin-right: 5px;background:#ff9900;color:#fff;border:#5ab1ef;"
                        @click="CancelAppointment(row.ID)"
                    >作废</Button>
                </template>
            </Table>
            <div class="page-wrap">
                <div class="page-wrap-total">共 {{total}} 条</div>
                <div>
                    <Page placement="top" :total="total" :current="current" @on-change="changePage" @on-page-size-change="changePageSize" show-sizer></Page>
                </div>
            </div>
        </Card>
        <Modal :mask-closable="false" v-model="Scheduling" title="排期查看" width="951">
            <Select v-model="paiqiStore" placeholder="请选择门店" style="width:200px;margin-right:20px">
                <Option v-for="item in shopList" :value="item.ID" :key="item.ID">{{ item.ShopName }}</Option>
            </Select>
            <!-- <DatePicker
                type="date"
                placeholder="起始时间"
                style="width: 200px;margin-right:20px"
                v-model="startDay"
                @on-change="startDayBtn"
            ></DatePicker>
            <DatePicker
                type="date"
                placeholder="结束时间"
                style="width: 200px;margin-right:20px"
                v-model="endDay"
                @on-change="endDayBtn"
            ></DatePicker>-->
            <Button icon="ios-search" @click="paiqiSearch" class="search-btn"  style="background:#009688;color:#fff">搜索</Button>
            <el-calendar :first-day-of-week="1">
                <template slot="dateCell" slot-scope="{date, data}">
                    <div>
                        <div class="calendar-day">{{ data.day.split('-').slice(1).join('/')}}</div>
                        <div v-for="item in paiqiList" :key="item.ID">
                            <div v-if="item.BookDate===data.day" style>
                                <div
                                   class="datestyle"
                                    @click="showInfor(item.BookDate,item.ShopID)"
                                >{{Number(item.num+1)}}</div>
                            </div>
                            <div v-else></div>
                        </div>
                    </div>
                </template>
            </el-calendar>
        </Modal>
        <Modal :mask-closable="false" v-model="isModal" :title="ModalTitle" width="700">
            <div v-if="isModal">
                <Form ref="formItem" :model="formItem" :rules="ruleValidate" :label-width="100">
                    <Row>
                        <i-col :lg="{ span: 24}">
                            <FormItem label="预约门店" prop="store">
                                <Select v-model="formItem.store" placeholder="请选择门店">
                                    <Option v-for="item in shopList" :value="item.ID" :key="item.ID">{{ item.ShopName }}</Option>
                                </Select>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 24}">
                            <FormItem label="预约人" prop="name">
                                <i-input v-model="formItem.name" placeholder="请输入预约人"></i-input>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 24}">
                            <FormItem label="联系电话" prop="phone">
                                <i-input v-model="formItem.phone" placeholder="请输入联系电话"></i-input>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 24}">
                            <FormItem label="预约项目" prop="project">
                                <CheckboxGroup v-model="formItem.project">
                                    <Checkbox v-for="item in project" :label="item.value" :key="item.value">{{ item.label }}</Checkbox>
                                </CheckboxGroup>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 24}">
                            <FormItem label="预约日期" prop="date">
                                <DatePicker type="date" value="yyyy-MM-dd" placeholder="请输入预约日期" v-model="formItem.date"></DatePicker>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 24}">
                            <FormItem label="预约时间" prop="time">
                                <Select v-model="formItem.time" placeholder="请选择预约时间" @on-open-change="ShopUnavailableHours">
                                    <Option v-for="item in timeList" :value="item" :key="item">{{ item }}</Option>
                                </Select>
                            </FormItem>
                        </i-col>
                    </Row>
                     <Row>
                        <i-col :lg="{ span: 24}">
                            <FormItem label="备注" prop="time">
                                 <i-input v-model="formItem.remark" placeholder="请输入联系电话"></i-input>
                            </FormItem>
                        </i-col>
                    </Row>
                </Form>
            </div>
            <div slot="footer">
                <Button size="large" @click="handleClose">取消</Button>
                <Button type="primary" size="large" @click="handleSubmit('formItem',ModalTitle)">确定</Button>
            </div>
        </Modal>
        <Modal :mask-closable="false" v-model="paiqiModal" width="400">
            <div v-if="paiqiModal">
                <ul class="modalList">
                    <li v-for="item in paiqiListContent" :key="item.ID">
                        <span>姓名：{{item.Name}}</span>
                        <span>项目：{{item.BusinessName}}</span>
                        <span>时间：{{item.BookTime}}:00</span>
                    </li>
                </ul>
                
            </div>
        </Modal>
    </div>
</template>

<script>
// import { cyclicRouting, getdate } from '@/util'
// import { getModulePermission } from '@/api/user'
import {
    shopData,
    NewAppointment,
    AppointmentList,
    CancelAppointment,
    ChangeAppointment,
    ShopUnavailableHours,
    GetTimeSchedule,
    GetAppointmentByDate
} from './service'
import GlobalTables from '@/components/GlobalTables'
import moment from 'moment'
export default {
    name: 'usersList',
    components: {
        GlobalTables
    },
    data() {
        return {
            // 时间列表
            timeList: [
                '08:00',
                '09:00',
                '10:00',
                '11:00',
                '12:00',
                '13:00',
                '14:00',
                '15:00',
                '16:00',
                '17:00',
                '18:00',
                '19:00',
                '20:00'
            ],

            // 查询项目
            project: [
                {
                    value: '1',
                    label: '问诊'
                },
                {
                    value: '2',
                    label: '推拿'
                },
                {
                    value: '3',
                    label: '针灸'
                },
                {
                    value: '4',
                    label: '艾灸'
                }
            ],
            // 状态
            state: [
                {
                    value: '1',
                    label: '预约中'
                },
                {
                    value: '2',
                    label: '已到店'
                },
                {
                    value: '3',
                    label: '已完成'
                },
                {
                    value: '4',
                    label: '已作废'
                }
            ],
            source: [
                {
                    value: '1',
                    label: '线上预约'
                },
                {
                    value: '2',
                    label: '电话预约'
                },
                {
                    value: '3',
                    label: '到店预约'
                }
            ],
            loading: false,
            isModal: false, //显示新增
            paiqiModal: false,
            formItem: {
                store: '',
                name: '',
                phone: '',
                project: [],
                date: '',
                time: '',
                state: '',
                remark:''
            }, //新增表单
            search: {
                state: '',
                source: '',
                project: [],
                date: ''
            }, //查询条件
            ModalTitle: '', //新增或修改
            ruleValidate: {
                store: [
                    {
                        required: true,
                        message: '请选择门店',
                        type: 'number',
                        trigger: 'change'
                    }
                ],
                name: [
                    {
                        required: true,
                        message: '请填写姓名',
                        trigger: 'blur'
                    }
                ],
                phone: [
                    {
                        required: true,
                        message: '请填写电话',
                        trigger: 'blur'
                    }
                ],
                project: [
                    {
                        required: true,
                        type: 'array',
                        min: 1,
                        message: '请选择预约项目',
                        trigger: 'change'
                    }
                ],
                date: [
                    {
                        required: true,
                        message: '请选择预约日期',
                        type: 'date',
                        trigger: 'change'
                    }
                ],
                time: [
                    {
                        required: true,
                        message: '请选择预约时间',
                        trigger: 'change'
                    }
                ]
            }, //表单验证
            shopList: [], //门店列表
            list: [],
            pagesize: 10,
            pageindex: 1,
            total: 0,
            current: 1,
            columns: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '预约门店',
                    width: 150,
                    key: 'ShopName'
                },
                {
                    title: '预约人',
                    width: 150,
                    key: 'Name'
                },
                {
                    title: '联系电话',
                    width: 150,
                    key: 'Phone'
                },
                {
                    title: '预约项目',
                    key: 'BusinessName'
                },
                {
                    title: '预约时间',
                    width: 150,
                    slot: 'BookDate'
                },
                {
                    title: '来源',
                    width: 100,
                    slot: 'InFrom'
                },
                {
                    title: '状态',
                    width: 80,
                    slot: 'State'
                },
                {
                    title: '申请时间',
                    width: 120,
                    slot: 'CreateTime'
                },
                {
                    title: '操作',
                    width: 130,
                    slot: 'action'
                }
            ],
            Scheduling: false,
            paiqiStore: 1,
            startDay: '',
            endDay: '',
            paiqiList: [],
            paiqiListContent: []
        }
    },
    filters: {
        //处理函数
        stateCn(value) {
            if (value === '1') {
                return '预约中'
            } else if (value === '2') {
                return '已到店'
            } else if (value === '3') {
                return '已完成'
            } else {
                return '已作废'
            }
        },
        InFromCn(value) {
            if (value === '1') {
                return '线上预约'
            } else if (value === '2') {
                return '电话预约'
            } else if (value === '3') {
                return '到店预约'
            }
        },
        BookDateCn(value) {
            console.log(value)
            return value.substring(0, 10)
        },
        CreateTimeCn(value) {
            return value.substring(0, 10)
        }
    },
    computed: {
        tableHeight() {
            // if (this.height) {
            //     return this.height
            // } else {
            return window.innerHeight - 240
            // }
        }
    },
    mounted() {
        this.shopData()
        this.AppointmentList()
        this.TodayDate()
        this.AnyDate(60)
        if (new Date().getDay() == 0) {
            this.startDay = new Date()
        } else {
            this.startDay = new Date()
        }
    },

    methods: {

        TodayDate() {
            let day = new Date()
            let mon = day.getMonth() + 1
            day.setTime(day.getTime())
            if (mon < 10) {
                mon = '0' + mon
            }
            let s2 = day.getFullYear() + '-' + mon + '-' + day.getDate()
            this.startDay = s2
        },
        AnyDate(AddDayCount) {
            var dd = new Date()
            dd.setDate(dd.getDate() + AddDayCount)
            let y = dd.getFullYear()
            let mon = dd.getMonth() + 1
            let d = dd.getDate()
            if (mon < 10) {
                mon = '0' + mon
            }
            this.endDay = y + '-' + mon + '-' + d
        },
        // 排期model
        SchedulingBtn() {
            this.Scheduling = true
            this.GetTimeSchedule()
        },
        // 获取排期信息
        async GetTimeSchedule() {
            let data = {
                shopid: this.paiqiStore,
                bookDateStart: this.startDay,
                bookDateEnd: this.endDay
            }
            console.log(data)
            if (data.shopid === '') {
                this.$Message.error('请选择门店！')
            }
            let res = await GetTimeSchedule(data)
            let arry = res.data.rows
            // this.paiqiList = res.data.rows
            arry.forEach(e => {
                e.BookDate = e.BookDate.substring(0, 10)
            })
            console.log(arry)
            var temp = {}
            for (var i in arry) {
                var key = arry[i].BookDate
                console.log(key)
                if (temp[key]) {
                    temp[key].num += 1
                    console.log(key)
                    temp[key].BookDate = arry[i].BookDate
                    temp[key].ID = arry[i].ID
                    temp[key].ShopID = arry[i].ShopID
                } else {
                    temp[key] = {}
                    temp[key].BookDate = arry[i].BookDate
                    temp[key].ID = arry[i].ID
                    temp[key].ShopID = arry[i].ShopID
                    temp[key].num = 0
                }
            }
            console.log(temp)

            var newArry = []
            for (var k in temp) {
                newArry.push(temp[k])
            }
            this.paiqiList = newArry
            console.log(newArry)

            console.log(this.paiqiList)
        },
        // 获取排期详细信息
        async showInfor(BookDate, ShopID) {
            let data = {
                shopid: ShopID,
                bookDate: BookDate
            }
            let res = await GetAppointmentByDate(data)
            if (res.state === 'success') {
                this.paiqiModal = true
                this.paiqiListContent = res.data.rows
                this.paiqiListContent.forEach(e => {
                    e.BusinessNameList = []
                    e.BusinessName = ''
                    e.Business.split(',').forEach(j => {
                        this.project.forEach(i => {
                            if (j == i.value) {
                                e.BusinessNameList.push(i.label)
                                e.BusinessName = e.BusinessNameList.join(',')
                            }
                        })
                    })
                })
            }
        },
        // 排期搜索
        paiqiSearch() {
            this.GetTimeSchedule()
        },
        // 获取门店列表
        async shopData() {
            let res = await shopData()
            this.shopList = res.data.rows
        },
        // 新建预约
        handleBtnClick() {
            this.ModalTitle = '新建预约'
            this.isModal = true
            this.formItem = {
                store: '',
                name: '',
                phone: '',
                project: [],
                date: '',
                time: '',
                state: '',
                remark:''
            }
        },
        /* 关闭对话框 */
        handleClose() {
            this.isModal = false
        },
        // 搜索
        handleSearch() {
            this.pageindex = 1
            this.loading = true
            this.AppointmentList()
        },
        // 新建预约提交/修改
        handleSubmit(name, ModalTitle) {
            this.$refs[name].validate(async valid => {
                if (valid) {
                    let data = {
                        ID: this.formItem.ID,
                        ShopID: this.formItem.store,
                        Name: this.formItem.name,
                        Phone: this.formItem.phone,
                        Business: this.formItem.project.join(','),
                        BookDate: moment(this.formItem.date).format(
                            'YYYY-MM-DD'
                        ),
                        BookTime: this.formItem.time.substring(0, 2),
                        State: this.formItem.state,
                        InFrom: '2',
                        Remark:this.formItem.remark
                    }
                    let res = {}
                    if (ModalTitle === '新建预约') {
                        res = await NewAppointment(data)
                    } else {
                        res = await ChangeAppointment(data)
                    }

                    if (res.state === 'success') {
                        this.$Message.success(res.message)
                        this.isModal = false
                        this.AppointmentList()
                    } else {
                        this.$Message.error(res.message)
                    }
                }
            })
        },
        // 获取列表
        async AppointmentList() {
            let data = {
                ID: '',
                ShopID: '',
                Name: '',
                Phone: '',
                Business: this.search.project.join(','),
                BookDate: this.search.date,
                BookTime: '',
                State: this.search.state,
                InFrom: this.search.source,
                pagesize: this.pagesize,
                pageindex: this.pageindex
            }
            let res = await AppointmentList(data)
            console.log(res)
            if (res.state === 'success') {
                this.list = res.data.rows
                this.total = res.data.records
                this.list.forEach(e => {
                    e.BusinessNameList = []
                    e.BusinessName = ''
                    e.Business.split(',').forEach(j => {
                        this.project.forEach(i => {
                            if (j == i.value) {
                                e.BusinessNameList.push(i.label)
                                e.BusinessName = e.BusinessNameList.join(',')
                            }
                        })
                    })
                })
            }
        },
        // 修改
        ChangeAppointment(row) {
            this.ModalTitle = '修改预约'
            this.isModal = true
            this.formItem = {
                store: row.ShopID,
                name: row.Name,
                phone: row.Phone,
                project: row.Business.split(','),
                date: row.BookDate,
                time: `${row.BookTime}:00`,
                state: row.State,
                ID: row.ID,
                remark:row.Remark
            }
        },
        // 取消预约
        CancelAppointment(ID) {
            let data = {
                ID: ID
            }
            this.$confirm('此操作将作废该条预约, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(async () => {
                    let res = await CancelAppointment(data)
                    if (res.state === 'success') {
                        this.$Message.success('已作废')
                        this.AppointmentList()
                    } else {
                        this.$Message.error(res.message)
                    }
                })
                .catch(() => {})
        },
        // 不可预约日期
        async ShopUnavailableHours(open) {
            console.log(open)
            if (this.formItem.store == '' || this.formItem.date == '') {
                if (open) {
                    this.timeList = []
                    this.$Message.error('请选择门店和预订日期')
                    return
                }
                return
            }
            this.timeList = [
                '08:00',
                '09:00',
                '10:00',
                '11:00',
                '12:00',
                '13:00',
                '14:00',
                '15:00',
                '16:00',
                '17:00',
                '18:00',
                '19:00',
                '20:00'
            ]
            let data = {
                shopid: this.formItem.store,
                bookDate: moment(this.formItem.date).format('YYYY-MM-DD')
            }
            let res = await ShopUnavailableHours(data)
            if (res.state == 'error') {
                this.$Message.error('请选择门店和预订日期')
            } else {
                let arr = []
                if (res.data.length > 0) {
                    this.timeList.forEach(i => {
                        res.data.forEach(e => {
                            console.log(i.substring(0, 2))
                            if (i.substring(0, 2) != e) {
                                arr.push(i)
                            }
                        })
                    })
                    this.timeList = arr
                } else {
                    this.timeList = [
                        '08:00',
                        '09:00',
                        '10:00',
                        '11:00',
                        '12:00',
                        '13:00',
                        '14:00',
                        '15:00',
                        '16:00',
                        '17:00',
                        '18:00',
                        '19:00',
                        '20:00'
                    ]
                }
            }
        },
        changePage(num) {
            this.pageindex = num
            this.loading = true
            this.AppointmentList()
        },
        changePageSize(num) {
            this.pagesize = num
            this.loading = true
            this.AppointmentList()
        }
    }
}
</script>

<style lang="less" scoped>
.datestyle{
    background-color: #f39800;
    color: #ffffff;
    border-radius: 50%;
    width: 30px;
    height: 30px;
    text-align: center;
    line-height: 30px;
}
.modalList{
    li{
        margin: 20px;
        span{
            display: inline-block;
            margin: 0 10px;
        }
    }
}
.table-top-wrapper {
    margin-left: 10px;
}
.is-selected {
    color: #1989fa;
}
.wrap {
    padding-bottom: 10px;
}
.page-wrap {
    position: fixed;
    bottom: 25px;
    left: 230px;
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
.page-wrap-total {
    border-radius: 3px;
    padding: 0 10px;
    height: 32px;
    line-height: 32px;
    margin: 0 20px;
    border: 1px solid #dcdee2;
    font-size: 12px;
}
.search-con {
    padding: 10px 0;
    .search {
        &-col {
            display: inline-block;
            width: 200px;
        }
        &-input {
            display: inline-block;
            width: 200px;
            margin-left: 2px;
        }
        &-btn {
            margin-left: 2px;
        }
    }
}
.list-btn {
    margin: 0 5px;
}
.delete-btn {
    background: #fc8675;
    border: none;
}
.edit-btn {
    background: #5ab1ef;
    border: none;
}
</style>